import {Dashboard} from "../pages/dashboard/dashboard.js";
import {Clients} from "../pages/clients/clients.js";
import {checkAuth} from "./auth.js";

let currentController = null;

async function loadPage(url) {
    const res = await fetch(url);
    return await res.text();
}

async function render() {
    checkAuth(); // 检查登录状态
    updateActiveLink(); // 更新导航高亮

    const path = location.hash || '#/dashboard';
    const route = routes[path];

    if (!route) {
        document.getElementById('app').innerHTML = '<h2>404 - 页面未找到</h2>';
        return;
    }

    // 执行卸载逻辑
    if (currentController?.onUnmount) {
        currentController.onUnmount();
    }

    // 加载模板
    document.getElementById('app').innerHTML = await loadPage(route.template);

    // 设置当前控制器
    currentController = route;

    // 执行加载逻辑
    if (route.onLoad) {
        route.onLoad();
    }
}

function updateActiveLink() {
    const path = location.hash || '#/dashboard';

    document.querySelectorAll('.nav-link').forEach(link => {
        if (link.getAttribute('href') === path) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });
}

const routes = {
    '#/dashboard': {
        template: '../pages/dashboard/dashboard.html',
        onLoad: () => Dashboard.mount(),
        onUnmount: () => Dashboard.unmount()
    },
    '#/clients': {
        template: '../pages/clients/clients.html',
        onLoad: () => Clients.mount(),
        onUnmount: () => Clients.unmount()
    }
};

window.addEventListener('hashchange', render);
window.addEventListener('load', render);
